package com.leyou.sms.mq;

import com.leyou.common.utils.JsonUtils;
import com.leyou.common.utils.RegexUtils;
import com.leyou.sms.config.SmsProperties;
import com.leyou.sms.utils.SmsUtils;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.Map;

import static com.leyou.common.constants.MQConstants.Exchange.SMS_EXCHANGE_NAME;
import static com.leyou.common.constants.MQConstants.Queue.SMS_VERIFY_CODE_QUEUE;
import static com.leyou.common.constants.MQConstants.RoutingKey.VERIFY_CODE_KEY;

@Component
public class MessageListener {

    @Autowired
    private SmsUtils smsUtils;

    @Autowired
    private SmsProperties smsProperties;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = SMS_VERIFY_CODE_QUEUE,durable = "true"),
            exchange = @Exchange(name = SMS_EXCHANGE_NAME,type = ExchangeTypes.TOPIC),
            key = VERIFY_CODE_KEY
    ))
    public void listenVerifyCodeMsg(Map<String,String> msg){
        try {
            if (CollectionUtils.isEmpty(msg)){
                return;
            }
            String phone = msg.get("phone");
            if(!RegexUtils.isPhone(phone)){
                return;
            }
            String code = msg.get("code");
            if(!RegexUtils.isVerifyCode(code)){
                return;
            }
            smsUtils.SendMessage(phone,smsProperties.getSignName(),
                    smsProperties.getVerifyCodeTemplate(), JsonUtils.toString(msg));
        }catch (Exception e){
            System.out.println("发送验证码信息失败！");
            return;
        }
    }
}
